<template>
    <div class="exerciseRecord">
      <div v-if="!addShow">
        <div><Button type="error" @click="addData('add')">＋ 新增</Button></div>
        <div style="padding-top: 20px">
          <Table border height="400" :columns="columns" :data="tableData">
            <template slot-scope="{ index, row }" slot="action">
              <Button
                type="primary"
                size="small"
                style="margin-right: 5px"
                @click="addData('see',row)"
              >查看</Button>
              <Button type="error" size="small" @click="remove(row)">删除</Button>
            </template>
          </Table>
          <div class="page">
            <Page
              :total="page.total"
              :page-size="page.pageSize"
              size="small"
              show-sizer
              show-total
              @on-change="currentHandle"
              @on-page-size-change="sizeChange"
              show-elevator
              :page-size-opts="allSize"
            />
          </div>
        </div>
      </div>
      <div v-if="addShow">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
          <Form-item label="锻炼时间" prop="createTime">
            <Date-picker v-if="addType == 'add'" type="datetime" v-model="formValidate.createTime" format="yyyy-MM-dd HH:mm:ss" @on-change="timeChange" placeholder="选择日期和时间" style="width: 200px"></Date-picker>
            <span v-else>{{formValidate.createTime}}</span>
          </Form-item>
          <Form-item label="锻炼内容" prop="content">
            <Input v-if="addType == 'add'" v-model="formValidate.content" type="textarea" :autosize="{minRows: 15,maxRows: 20}" placeholder="请输入锻炼内容"></Input>
            <span v-else>{{formValidate.content}}</span>
          </Form-item>
          <Form-item label="上传照片" prop="uploadList">
            <div class="uploadCla">
              <div class="upload-list" v-if="formValidate.uploadList.length > 0">
                <div class="upload-list-item" v-for="(item, index) in formValidate.uploadList">
                  <img :src="item" style="width: 128px;height: 128px">
                  <div class="upload-list-cover" v-if="addType == 'add'">
                    <Icon type="ios-trash-outline" size="20" color="#ffffff" @click.native="handleRemove(index)"></Icon>
                  </div>
                </div>
              </div>
              <Upload
                v-if ="addType == 'add'"
                :show-upload-list="false"
                ref="upload"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png','bmp']"
                :max-size="2048"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                :headers="accessToken"
                :multiple="true"
                type="drag"
                :action="action"
                style="display: inline-block;width:128px;">
                <div style="width: 128px;height:128px;line-height: 128px;">
                  <span style="font-size: 25px">+</span>
                </div>
              </Upload>
              <span style="font-size: 14px;color: #B3B3B3" v-if ="addType == 'add'">只能上传jpg/png/bmp文件，且不超过2MB（最多可上传3张图片）</span>
            </div>
          </Form-item>
          <Form-item>
            <Button type="text" @click="goBack">返回</Button>
            <Button type="error" v-if="addType == 'add'" @click="handleReset('formValidate')" style="margin-left: 8px">提交</Button>
          </Form-item>
        </Form>
      </div>
    </div>
</template>

<script>
  import {getExercisePage,addExerciseRow,addExerciseImg,delExerciseId} from "@/api/yk_record";
  import { commonUrl } from '@/plugins/request';
    export default {
        name: "exerciseRecord",
      data(){
        const validateUpload = (rule, value, callback) => {
          if(this.formValidate.uploadList && this.formValidate.uploadList.length === 0) {
            callback(new Error('请上传图片'))
          } else {
            callback()
          }
        }
        return{
          page: { // 请求参数
            total: 0,
            pageNumber: 1,
            pageSize: 10
          },
          columns:[
            {
              type: 'index',
              width: 200,
              align: 'center'
            },
            {
              title: '锻炼时间',
              key: 'createTime',
              align: "center",
            },
            {
              title: '锻炼内容',
              key: 'content',
              align: "center",
            },
            {
              title: "操作",
              slot: "action",
              minWidth: 100,
              align: "center",
            },
          ],
          tableData:[],
          allSize: [5, 10, 15, 20],
          addShow: false,
          addType:'',
          rowData:{},
          action:commonUrl + '/common/common/upload/file',
          accessToken: {}, // 验证token
          formValidate: {
            createTime: '',
            content: '',
            pic: '',
              uploadList:[]
          },
          ruleValidate: {
            createTime: [
              { required: true, message: '请选择锻炼时间', trigger: 'change' }
            ],
            content: [
              { required: true, message: '请输入锻炼内容', trigger: 'blur' }
            ],
              uploadList: [
              { required: true, validator: validateUpload, trigger: 'change' }
            ],
          }
        }
      },
      mounted(){
        this.accessToken.accessToken = localStorage.getItem('accessToken');
        this.getExercisePageData()
      },
      methods:{
        //获取当前页码
        currentHandle(current) {
          this.page.pageNumber = current;
          this.getExpertList();
        },
        sizeChange(size) {
          this.page.pageSize = size;
          this.getExpertList();
        },
        getExercisePageData(){
          getExercisePage(this.page).then((res =>{
            if(res.code == '200'){
              this.tableData = res.result.records
              this.page.total = Number(res.result.total)
            }else {
              this.$Message.error(res.message || '获取失败!');
            }
          }))
        },
        timeChange(e){
          this.formValidate.createTime = e
        },
        goBack(){
          this.formValidate = {
            createTime: '',
            content: '',
            pic: '',
            uploadList:[]
          }
          this.addShow = false
          this.addType = ''
        },
        addData(type, row){
          console.log(type,'----');
          this.addShow = true
          this.addType = type
          this.rowData = type == 'see' ? row : ''
          if(type == 'see'){
            this.formValidate.content = row.content
            this.formValidate.createTime = row.createTime
            this.formValidate.uploadList = row.pic.split(',')
          }
        },
        handleReset(name){
          this.$refs[name].validate((valid) => {
            if (valid) {
              this.formValidate.pic = this.formValidate.uploadList.join(',')
              let params = {
                createTime: this.formValidate.createTime,
                content: this.formValidate.content,
                pic: this.formValidate.pic,
              }
              addExerciseRow(params).then((res) =>{
                if(res.code){
                  this.$Message.success('提交成功!');
                  this.goBack()
                  this.getExercisePageData()
                }else {
                  this.$Message.error(res.message || '提交失败!');
                }
              })
            }
          })
        },
        remove(row){
          delExerciseId(row.id).then((res) =>{
            if(res.code == '200'){
              this.$Message.success("删除成功");
              this.getExercisePageData()
            }else {
              this.$Message.error(res.message || '删除失败!');
            }
          })
        },
        handleRemove (index) {
          this.formValidate.uploadList.splice(index, 1)
        },
        handleSuccess (res, file) {
          this.formValidate.uploadList.push(res.result)
        },
        handleFormatError (file) {
          this.$Notice.warning({
            title: '文件格式不正确',
            desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
          });
        },
        handleMaxSize (file) {
          this.$Notice.warning({
            title: '超出文件大小限制',
            desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
          });
        },
        handleBeforeUpload () {
          const check = this.formValidate.uploadList.length < 4;
          if (!check) {
            this.$Notice.warning({
              title: '最多只能上传 3 张图片。'
            });
          }
          return check;
        }
      }
    }
</script>

<style lang="less" scoped>
  .exerciseRecord {
    width: calc(1650 / 1920 * 100vw);
    background: #fff;
    position: absolute;
    top: calc(288 / 1920 * 100vw);
    left: calc(240 / 1920 * 100vw);
    padding: calc(10 / 1920 * 50vw) calc(40 / 1920 * 50vw)
    calc(40 / 1920 * 50vw);
  .addBtn {
    padding: calc(10 / 1920 * 100vw) calc(20 / 1920 * 100vw);
    background: #fd5151;
    line-height: calc(32 / 1920 * 100vw);
    text-align: center;
    border-radius: calc(4 / 1920 * 100vw);
    color: #fff;
    border: none;
  }
    .page{
      padding-top: 20px;
      display:flex;
      justify-content: flex-end;
    }
    .uploadCla{
      display: flex;
      justify-content: flex-start;
      align-items: self-end;
      .upload-list{
        display: flex;
        text-align: center;
        border-radius: 4px;
        background: #fff;
        .upload-list-item{
          width: 128px;
          height: 128px;
          line-height: 128px;
          margin-right: 4px;
          overflow: hidden;
          position: relative;
        }
        .upload-list-cover{
          display: none;
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          background: rgba(0, 0, 0, 0.6);
        }
      }
      .upload-list-item:hover .upload-list-cover {
        display: block;
      }
    }
  }
</style>
<style lang="less">
  .exerciseRecord .ivu-upload .ivu-upload-drag {
    border: none;
  }
</style>
